package cn.com.sixboy.controller;

import cn.com.sixboy.entity.Student;
import cn.com.sixboy.service.common.IndexService;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Sam.Zheng <zcl1866@sina.com>
 * @date 2013-4-27 16:21:19
 * @version <v0.1>
 * @copyright SixBoy
 */
@Controller
@RequestMapping("/index")
public class IndexController {

    static Logger log = Logger.getLogger(IndexController.class);
    @Autowired
    private IndexService indexService;
    
    public IndexController(){
       
    }

    @RequestMapping(value = "/addStudent", method = RequestMethod.POST,produces="application/json")
    public @ResponseBody String addStudent(@RequestBody Student stu) {
        
        /**
         * @RequestBody Student stu 从页面传过来的json 对象 被直接转化成学生对象，不建议直接使用该对象直接调用持久化对象方法保存数据，参考下列方法
         * */
        Student student = new Student(); //新创建的准备要插入的实体对象
        cn.com.sixboy.entity.Class clas = (cn.com.sixboy.entity.Class) indexService. 
                    querySingleEntity(cn.com.sixboy.entity.Class.class, stu.getS_class().getId());//初始化学生所属班级对象，使其处于受控状态
        student.setName(stu.getName()); //给属性赋值
        student.setS_class(clas);//给班级属性赋值
        boolean b = indexService.addStudent(student); // 保存返回值
        if (b) {
            return "1";
        } else {
            return "0";
        }
    }

    @RequestMapping(value = "/indexStu")
    public String indexStudent(Model model) {
        List<Student> list = indexService.findAllStudent(); //查询所有学生对象
        model.addAttribute("stus", list); //赋值给属性stus，传值到jsp页面中，可用jstl在页面输出详细值
        return "index/indexstu"; //返回到指定到视图(indexstu.jsp)
    }
    @RequestMapping(value = "/goAddStu")
    public String goAddStu(Model model) {
        List<cn.com.sixboy.entity.Class> list = indexService.queryAllEntity(
                "findAllClasses", true);
        StringWriter sw = new StringWriter();
        Iterator iter = list.iterator();
        while (iter.hasNext()) {
            cn.com.sixboy.entity.Class cls = (cn.com.sixboy.entity.Class) iter
                    .next();
            sw.append("<option").append(" value='").append(cls.getId() + "")
                    .append("'>").append(cls.getClassName())
                    .append("</option>");
        }
        model.addAttribute("options", sw.toString());//拼接字符串后，输出到jsp 页面中
        return "index/goaddstu";
    }

    @RequestMapping(value = "/goAddClass")
    public String goAddClass(Model model) {
        List<cn.com.sixboy.entity.Class> list = indexService.queryAllEntity(
                "findAllClasses", true);
        model.addAttribute("list", list);
        return "index/goaddclass";
    }

    @RequestMapping(value = "/addclass", method = RequestMethod.POST)
    public String addClass(Model model, cn.com.sixboy.entity.Class clas) {
        log.debug(clas);
        if (indexService.add(clas)) {
            List<cn.com.sixboy.entity.Class> list = indexService
                    .queryAllEntity("findAllClasses", true);
            model.addAttribute("list", list);
        } else {
            return "error/500";
        }
        return "index/goaddclass";
    }

    @RequestMapping(value = "/delclass/{id}", method = RequestMethod.GET,consumes="text/html;charset=utf-8")
    public @ResponseBody
    String delClass(@PathVariable int id) {
        cn.com.sixboy.entity.Class clas = (cn.com.sixboy.entity.Class) indexService.querySingleEntity(cn.com.sixboy.entity.Class.class, id);
        if(clas!=null&&clas.getStudents().size()>0){
            return "不允许直接删除父对象";//禁止一对多映射直接删除
        }
        if (indexService.delete(clas)) {
            return "1";
        } else {
            return "0";
        }
    }
    
    @RequestMapping(value = "/delStu/{id}", method = RequestMethod.GET)
    public @ResponseBody String delStu(@PathVariable int id) {
        Student stu = (Student) indexService.querySingleEntity(Student.class, id);
        if(stu.getS_class()!=null){
            stu.setS_class(null);
            indexService.delete(stu);
        }
        if (indexService.delete(stu)) {
            return "1";
        } else {
            return "0";
        }
    }

    @RequestMapping(value = "/goModfiyStu/{id}", method = RequestMethod.GET)
    public String modfiyStu(@PathVariable int id, Model model) {
        Student stu = (Student) indexService.querySingleEntity(Student.class,
                id);
        List<cn.com.sixboy.entity.Class> list = indexService.queryAllEntity(
                "findAllClasses", true);
        Iterator iter = list.iterator();
        StringWriter sw = new StringWriter();
        while (iter.hasNext()) {
            cn.com.sixboy.entity.Class cls = (cn.com.sixboy.entity.Class) iter
                    .next();
            String selected = "";
            if (stu.getS_class().getId() == cls.getId()) {
                selected = "selected ";
            }
            sw.append("<option").append(" value='").append(cls.getId() + "")
                    .append("'").append(selected).append(">")
                    .append(cls.getClassName()).append("</option>");
        }
        model.addAttribute("stu", stu);
        model.addAttribute("options", sw.toString());
        return "index/gomodifystu";
    }

    @RequestMapping(value = "/doModfiyStu", method = RequestMethod.POST)
    public @ResponseBody
    int doModfiyStu(@RequestBody Student stu) {
        // System.out.println(stu.getId()+":"+stu.getName()+":"+stu.getS_class().getId());
        boolean b = indexService.update(stu);
        if (b) {
            return 1;
        } else {
            return 0;
        }
    }
    @RequestMapping(value = "/user/login", method = RequestMethod.GET)
    public String reload(){
         return "user/login";
    }
    
    @RequestMapping(value = "/user/info", method = RequestMethod.GET)
    public String userinfo(){
         return "user/info";
    }
   @RequestMapping(value = "/findStu/{studentName}", method = RequestMethod.GET)
    public String queryStudent(@PathVariable String studentName,Model model){
         List list =  indexService.findAllStudentByName(studentName);//查找学生
         model.addAttribute("stus", list); //赋值给属性stus，传值到jsp页面中，可用jstl在页面输出详细值
         return "index/indexstu"; //返回到指定到视图(indexstu.jsp)
    }
   
    @RequestMapping(value = "/findClass/{className}", method = RequestMethod.GET)
    public String queryClass(@PathVariable String className,Model model) { //查找班级
        List<cn.com.sixboy.entity.Class> list = indexService.findAllClassByName(className);
        model.addAttribute("list", list);
        return "index/goaddclass";
    }
    @RequestMapping(value="/tpl")
    public String goTpl(){

        return "index/indexstu";
    }
}
